var g_gameDataManager = require("g_gameDataManager");
var MessageManager = require("MessageManager");
var prcmd = require("ProtoCmdID")
cc.Class({
    extends: cc.Component,

    properties: {
        overPlayerPrefab:cc.Prefab,
    },

    // use this for initialization
    onLoad: function () {
        var msg = g_gameDataManager.msgTemp;
        this.initData();
        this.initView(msg);
    },

    initData:function()
    {
        NotificationCenter.on(prcmd.READY_ROOM,this.readyRoom,this);
        NotificationCenter.on(prcmd.KICK_PLAYER,this.kicked,this);
    },


    initView:function(jMsg)
    {
        var rolesInfo = jMsg.data.rolesInfo;
        var startPos = cc.p(0,460);
        for(var i=0;i<rolesInfo.length;i++)
        {
            var obj = rolesInfo[i];
            var overPlayerNode = cc.instantiate(this.overPlayerPrefab);
            var pCon = overPlayerNode.getComponent(require('OverPlayer'));
            pCon.setAttr(obj.headUrl,obj.score);
            var pos = startPos;
            pos.y -= 190;
            overPlayerNode.setPosition(pos);
            this.node.addChild(overPlayerNode);
        }
    },

    restartCallBack:function(event)
    {
        var msg = {
            'cmdID': prcmd.READY_ROOM,
            'data': {
                'isReady': true
            }
        };
        MessageManager.sendMessage(JSON.stringify(msg));
    },

    readyRoom:function(eventObj)
    {
        var roleLis = eventObj.msg.data.rolesInfo;
        for(var i=0;i<roleLis.length;i++)
        {
            var obj = roleLis[i];
            if (obj.isReady &&  g_gameDataManager.getUserID() == obj.usrID) {
                g_gameDataManager.msgTemp = eventObj.msg;
                cc.director.loadScene('RoomScene');
                break;
            }
        }
    },


    kicked:function(eventObj)
    {
        var data = eventObj.msg.data;
        if(data.kickedUsrID == g_gameDataManager.getUserID())
        {
            var reason = data.reason;
            if(reason == prcmd.KICKED_BY_OVERTIME)
            {
                console.log("you were kicked for long time not start game");
            }
            else if(reason == prcmd.KICKED_BY_OTHER)
            {
                var usrName = data.usrName;
                console.log("you were kicked by"+usrName);
            }
            else if(reason == prcmd.KICKED_BY_SELF)
            {
                console.log("self into msg");
            }
            g_gameDataManager.msgTemp = data.hallInfo;
            cc.director.loadScene('HomeScene');
        }
        else
        {
            var kickMsg = '玩家['+data.kickedUsrName+']'+'被['+data.byUsrName+'] 踢出房间';
            console.log(kickMsg);
        }
    },

    onDestroy:function()
    {
        NotificationCenter.off(prcmd.KICK_PLAYER,this.kicked,this);
        NotificationCenter.off(prcmd.READY_ROOM,this.readyRoom,this);
    },

});
